"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/5/30 8:56
@Description : 
1.编写程序实现用户的注册和登录功能，要求用户名不能重复，密码为六位并且加密处理，用户可选择是登录还是注册
users.csv
"""
import csv
import hashlib


class UserChoicesError(Exception):
    pass


welcome_info = """
*************xx后台管理系统******************
1.注册
2.登录
********************************************
"""
try:
    while True:
        print(welcome_info)
        user_input = input('请选择(Q退出):')
        if user_input.upper() == 'Q':
            break
        match user_input:
            case '1':
                with open('users.csv', 'r+', newline='') as f:
                    dict_reader = csv.DictReader(f)
                    while True:
                        username = input('请输入用户名:')
                        for user in dict_reader:
                            if user['username'] == username:
                                print('用户名已存在!!!')
                                break
                        else:
                            password = input('请输入密码:')
                            # 加密密码
                            hex_password = hashlib.md5(password.encode('utf-8')).hexdigest()
                            usr = {
                                'username': username,
                                'password': hex_password,
                            }
                            # 将数据写出到csv文件
                            dict_writer = csv.DictWriter(f, fieldnames=usr.keys())
                            dict_writer.writerow(usr)
                            break

            case '2':
                username = input('请输入用户名:')
                password = input('请输入密码:')
                # 加密密码
                hex_password = hashlib.md5(password.encode('utf-8')).hexdigest()
                with open('users.csv', 'r', newline='') as f:
                    users = csv.DictReader(f)
                    for user in users:
                        if user['username'] == username and user['password'] == hex_password:
                            print('认证通过')
                            break
                    else:
                        print('用户名或密码错误')
            case _:
                raise UserChoicesError()
except UserChoicesError:
    print('您选择的功能不存在,程序退出')
